package com.example.netttytest.mychat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class MyChatClient {
    public static void main(String[] args) throws Exception {
        //客户端需要一个事件循环组
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //创建客户端启动对象
            //注意客户端使用的不是 ServerBootstrap 而是 Bootstrap
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(group) //设置线程组
                    .channel(NioSocketChannel.class) // 使用 NioSocketChannel 作为客户端的通道实现
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //向pipeline加入解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //向pipeline加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自己的业务handler
                            pipeline.addLast(new MyChatClientHandler());
                        }
                    });
            //启动客户端去连接服务器端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9002).sync();
            //得到channel
            Channel channel = channelFuture.channel();
            //客户端需要在控制台输入信息
            Scanner scan = new Scanner(System.in);
            while (true) {
                System.out.println("~~~~~~~~~~~~~~~~~ ========== " + channel.localAddress() + "========= ~~~~~~~~~~~");
                System.out.println("您选择了群发消息 1：群发 输入 1  2：私聊 2");
                String flag = scan.next();
                if (flag.equalsIgnoreCase("1")) {
                    System.out.println("您选择了群发消息，将会通知到所有人,请输入您要发送的消息");
                    String msgq = scan.next();
                    //通过channel发送消息到服务器 就是 你发送了数据 所有人都可以有
                    channel.writeAndFlush("群发：" + msgq);
                } else if (flag.equalsIgnoreCase("2")) {
                    System.out.println("请输入私聊给默认的地址 ");
                    String address = scan.next();
                    System.out.println("请输入您要发送的消息");
                    String msgs = scan.next();
                    channel.writeAndFlush(address + "," + msgs);
                }
            }
        } finally {
            group.shutdownGracefully();
        }
    }
}
